<template>
  <div class="box" v-if="bol">
    <van-nav-bar
      title="刷题"
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <template #left> <i class="iconfont iconbtn_nav_back"></i></template>
      <template #right>答题卡</template>
    </van-nav-bar>
    <div class="main">
      <p>
        <span>
          {{ active + 1 }}
          【 {{ questionType[questionInfo.type - 1] }} 】
        </span>
        {{ questionInfo.title }}
      </p>
      <div class="label">
        <span
          class="item"
          v-for="(item, index) in questionInfo.tag"
          :key="index"
          >{{ item }}</span
        >
      </div>
    </div>
    <!-- 单选项 -->
    <div class="select" v-if="questionInfo.type === 1">
      <div
        class="button active"
        :class="singleAnswer === index ? 'active' : 'noActive'"
        v-for="(item, index) in questionInfo.option"
        :key="index"
        @click="checkEvent(index)"
      >
        {{ option[index] }}. {{ item }}
        <div
          class="mask"
          :class="[
            {
              success:
                (option[singleAnswer] === returnAnswer.singleAnswer &&
                  index === singleAnswer) ||
                option[index] === returnAnswer.singleAnswer,
              error:
                index === singleAnswer &&
                option[singleAnswer] != returnAnswer.singleAnswer
            }
          ]"
          v-if="
            isSubmit &&
              (option[singleAnswer] === returnAnswer.singleAnswer ||
                singleAnswer === index ||
                option[index] === returnAnswer.singleAnswer)
          "
        ></div>
      </div>
    </div>
    <!-- 多选项 -->
    <div class="select" v-else-if="questionInfo.type === 2">
      <div
        class="button active"
        :class="multipleAnswer.indexOf(index) != -1 ? 'active' : 'noActive'"
        v-for="(item, index) in questionInfo.option"
        :key="index"
        @click="checkEvent(index)"
      >
        {{ option[index] }}. {{ item }}
        <div
          class="mask"
          :class="[
            {
              success: checkboxMask.includes(index),
              error:
                multipleAnswer.includes(index) &&
                !returnAnswer.multipleAnswer.includes(option[index])
            }
          ]"
          v-if="
            isSubmit &&
              (option[singleAnswer] === returnAnswer.singleAnswer ||
                singleAnswer === index ||
                option[index] === returnAnswer.singleAnswer)
          "
        ></div>
      </div>
    </div>
    <!-- // 简答题录音组件 -->
    <div class="radio" v-else-if="questionInfo.type === 3">
      <ShortAnswer></ShortAnswer>
    </div>
    <!-- 答案解析 -->
    <div class="answer" v-if="isSubmit">
      <Answer :answer="returnAnswer"></Answer>
    </div>
    <div class="footer">
      <div class="left">
        <span class="item" :class="idActive ? 'isActive' : ''">
          <van-icon class="que" :name="idActive ? 'star' : 'star-o'" />
          <span class="text" @click="collect">收藏</span>
        </span>
        <span class="item">
          <van-icon class="que" name="edit" />
          <span class="text" @click="showComment">反馈</span>
        </span>
      </div>
      <div>
        <span> {{ lenLen }}</span
        >/{{ allId.length }}
      </div>
      <div class="btn">
        <van-button v-if="!isSubmit" :disabled="submitAndNext" @click="submit">
          提交
        </van-button>
        <van-button v-else @click="nextQuestion">
          下一题
        </van-button>
      </div>
    </div>
    <CommentDialog ref="dialog"></CommentDialog>
    <van-dialog
      @confirm="edit"
      v-model="editShow"
      title="题目未做完,确认退出码"
      show-cancel-button
      class="editDialog"
    >
      <p>共 {{ allId.length }} 题</p>
      <p>已答 {{ lenLen }} 题</p>
      <p>
        正确<span class="success"> {{ successNum }} </span>题
      </p>
      <p>
        错误 <span class="error"> {{ errorNum }} </span>题
      </p>
    </van-dialog>
  </div>
</template>
<script>
import {
  interviewQuestions,
  questionsSubmit,
  questions,
  questionsCollect
} from '@/api/question.js'
import Answer from './answer.vue'
import ShortAnswer from './shortAnswer.vue'
import CommentDialog from './comment.vue'
export default {
  name: '',
  components: { Answer, ShortAnswer, CommentDialog },
  data () {
    return {
      icon: {
        active: 'https://img01.yzcdn.cn/vant/user-active.png',
        inactive: 'https://img01.yzcdn.cn/vant/user-inactive.png'
      },
      // 题目类型枚举
      questionType: ['单选', '多选', '简答'],
      // 试题详情
      questionInfo: {},
      option: { 0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E' },
      // 收藏按钮css切换
      idActive: false,
      // 是否点击提交
      isSubmit: false,
      // 遮罩层是否显示
      mask: false,
      // 首次请求面试题需要的数据
      params: this.$route.params,
      // 单选答案
      singleAnswer: -1,
      // 多选答案
      multipleAnswer: [],
      // 试题id
      id: this.$route.params.id || localStorage.getItem('questionId') || '',
      // 返回的答案解析
      returnAnswer: {},
      // 题目索引
      questionIndex: this.$route.params.index || 0,
      // 所有面试题的id
      allId: localStorage.getItem('allId')
        ? JSON.parse(localStorage.getItem('allId'))
        : [],
      // 本地存储的题目索引
      localQuestion: localStorage.getItem('localQuestion') || [],
      // 做完的题目数组
      len: [],
      lenLen: localStorage.getItem('lenLen') || '0',
      isOption: true,
      // 公司id
      companyId: this.$route.query.companyId || '',
      bol: false,
      successNum: 0,
      errorNum: 0,
      allNum: 0,
      editShow: false
    }
  },
  created () {
    this.$toast.loading({ message: '加载中' })
    // 没有id就请求所有题,有就拿id请求
    if (this.id === '' || this.id === 'undefined') {
      this.getQuestions()
    } else {
      this.getData()
    }
    this.bol = true
  },
  computed: {
    // 不选择选项 就返回 false 不能提交
    submitAndNext () {
      if (this.questionInfo.type === 1) {
        return this.singleAnswer < 0
      } else {
        return this.multipleAnswer.length <= 0
      }
    },
    // 多选正确答案数组
    checkboxMask () {
      const arr = ['A', 'B', 'C', 'D', 'E']
      return this.returnAnswer.multipleAnswer.map(item => {
        return arr.indexOf(item)
      })
    },
    active () {
      let idx = ''
      this.allId.forEach((item, index) => {
        if (item.id === +this.id) {
          idx = index
        }
      })
      return idx
    }
  },
  methods: {
    myQuestion () {
      return JSON.parse(localStorage.getItem('localQuestion')) || []
    },
    // 头部左箭头返回到上个页面
    onClickLeft () {
      this.$dialog
        .confirm({
          title: '这是一个寂寞的天',
          message: '确认退出答题吗 ?'
        })
        .then(() => {
          this.$router.push('/questions?myAnswer=' + this.lenLen)
          localStorage.setItem('questionId', '')
          localStorage.setItem('lenLen', 0)
          localStorage.setItem('localQuestion', JSON.stringify([]))
        })
        .catch(() => {})
    },
    // 答题卡
    onClickRight () {
      this.$router.push('/answerCard?id=' + this.id)
    },
    // 获取面试题
    async getQuestions () {
      const res = await interviewQuestions(this.params)
      this.allId = res.data
      if (!localStorage.getItem('allId')) {
        localStorage.setItem('allId', JSON.stringify(res.data))
      }
      this.questionInfo = res.data[this.questionIndex].detail
      this.id = res.data[this.questionIndex].id
      localStorage.setItem('questionId', res.data[this.questionIndex].id)
      this.$nextTick(() => {
        this.$toast.clear()
      })
    },
    // (根据id查询试题)
    async getData () {
      localStorage.setItem('questionId', this.id)
      localStorage.setItem('questionIndex', this.questionIndex)
      const res = await questions(this.id)
      this.questionInfo = res.data
      this.$nextTick(() => {
        this.$toast.clear()
      })
    },
    // 下一题
    edit () {
      this.editShow = false
      localStorage.setItem('questionId', '')
      localStorage.setItem('lenLen', 0)
      localStorage.setItem('localQuestion', JSON.stringify([]))
      this.$router.push('/questions?myAnswer=' + this.lenLen)
    },
    nextQuestion () {
      console.log(this.allId.length)
      console.log(this.active)
      if (this.allId.length === this.active + 1) {
        console.log(2)
        this.editShow = true
        // this.$dialog
        //   .confirm({
        //     title: '这是一个寂寞的天',
        //     message: '最后一题了,换个职位试试吧 ?'
        //   })
        //   .then(() => {
        //     this.$router.push('/questions?myAnswer=' + this.lenLen)
        // localStorage.setItem('questionId', '')
        // localStorage.setItem('lenLen', 0)
        // localStorage.setItem('localQuestion', JSON.stringify([]))
        //   })
        //   .catch(() => {})
      } else {
        console.log(1)
        // console.log('allId', this.allId.length)
        // console.log('active', this.active)
        this.isOption = true
        this.isSubmit = false
        this.questionIndex++
        this.id = this.allId[this.questionIndex].id
        this.getData()
        this.idActive = false
        this.singleAnswer = '-1'
      }
    },
    // 收藏功能
    async collect () {
      this.idActive = !this.idActive
      await questionsCollect({ id: this.id })
    },
    //  选择答案时
    checkEvent (index) {
      if (this.isOption) {
        if (this.questionInfo.type === 1) {
          this.singleAnswer = index
        } else {
          if (this.multipleAnswer.includes(index)) {
            this.multipleAnswer.splice(this.multipleAnswer.indexOf(index), 1)
          } else {
            this.multipleAnswer.push(index)
          }
        }
      }
    },
    // 反馈组件
    showComment () {
      this.$refs.dialog.question = this.id
      this.$refs.dialog.show = true
    },
    // 提交
    async submit () {
      let res = ''
      if (this.questionInfo.type === 1) {
        res = await questionsSubmit({
          id: this.id,
          singleAnswer: this.option[this.singleAnswer]
        })
      } else {
        const temp = this.multipleAnswer.map(item => {
          return this.option[item]
        })
        res = await questionsSubmit({
          id: this.id,
          multipleAnswer: temp,
          singleAnswer: ''
        })
      }
      this.isSubmit = true
      this.isOption = false
      this.returnAnswer = res.data
      // 本地存储已答试题信息
      if (typeof this.localQuestion === 'string') {
        this.localQuestion = JSON.parse(this.localQuestion)
      }
      // 如果本地有数据遍历重复的不添加
      if (this.localQuestion.length > 0) {
        if (this.localQuestion.some(v => v.id === this.id)) {
          this.localQuestion.forEach((item, index) => {
            if (item.id === this.id) {
              this.localQuestion[index].isRight = res.data.isRight
            }
          })
        } else {
          this.localQuestion.push({
            id: +this.id,
            type: this.questionInfo.type,
            isRight: res.data.isRight,
            index: this.questionIndex
          })
        }
      } else {
        this.localQuestion.push({
          id: this.id,
          type: this.questionInfo.type,
          isRight: res.data.isRight,
          index: this.questionIndex
        })
      }
      localStorage.setItem('localQuestion', JSON.stringify(this.localQuestion))
      const lenA = this.allId.filter(item => {
        return this.localQuestion.some(v => {
          return item.id === v.id && !v.isRight
        })
      })
      this.errorNum = lenA.length
      const lenB = this.allId.filter(item => {
        return this.localQuestion.some(v => item.id === v.id && v.isRight)
      })
      this.successNum = lenB.length
      this.len = [...lenA, ...lenB]
      this.lenLen = this.len.length
      localStorage.setItem('lenLen', this.lenLen)
    }
  }
}
</script>
<style scoped lang="less">
.iconbtn_nav_back {
  font-size: 80px;
}
.box {
  height: 100%;
  background-color: #fff;
  position: relative;
  display: flex;
  flex-direction: column;
  .main {
    margin: 30px 30px 20px;
    .label {
      margin-top: 20px;
      .item {
        padding: 6px;
        margin: 5px;
        background: #f7f4f5;
        border-radius: 6px;
        font-size: 24px;
        color: #b4b4bd;
      }
    }
  }
  .select {
    padding: 48px;
    .button {
      position: relative;
      margin-top: 48px;
      width: 100%;
      padding: 15px;
      line-height: 50px;
      text-indent: 1em;
      border: 2px solid #f7f4f5;
      border-radius: 8px;
      &.active {
        border: 2px solid #b4b4bd;
      }
      &.noActive {
        border: 2px solid #f7f4f5;
      }
      .mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0.3;

        border: 2px solid pink;
        border-radius: 8px;
        &.success {
          background: #b0e446 url('~@/assets/icon_zhengque@2x.png') no-repeat
            560px 10px;
          background-size: 60px;
        }
        &.error {
          background: #e419e7 url('~@/assets/icon_cuowu@2x.png') no-repeat 560px
            10px;
          background-size: 60px;
        }
        &.info {
          background-color: pink;
        }
      }
    }
  }
  .radio {
    width: 100%;
    flex: 1;
    background-color: #f8f6f5;
  }
  .footer {
    position: fixed;
    display: flex;
    bottom: 0;
    width: 100%;
    height: 100px;
    padding: 0 30px;
    background-color: #fff;
    z-index: 99;
    justify-content: space-between;
    align-items: center;
    .left {
      display: flex;
      justify-content: start;

      .item {
        text-align: center;
        margin-right: 30px;
        color: #b4b4bd;
        &.isActive {
          color: red;
        }

        .que {
          display: block;
        }
        .text {
          font-size: 24px;
        }
      }
    }
    .van-button {
      width: 196px;
      height: 80px;
      background: #e40137;
      border-radius: 14px;
      color: #fff;
    }
  }
  .editDialog {
    text-align: center;
    line-height: 60px;
    .success {
      color: yellowgreen;
    }
    .error {
      color: pink;
    }
  }
}
</style>
